//
//  FeedbackViewController.m
//  HTHappySale
//
//  Created by 曾华桥 on 17/9/27.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "FeedbackViewController.h"
#import "MainViewController.h"

#import "HTTPPromise+Me.h"

#import <Masonry.h>
#import "AppUtil.h"
@interface FeedbackViewController ()<UITextViewDelegate,UITextFieldDelegate>
{
    UILabel *subTitle1;
    UILabel *subTitle2;
    UIView *subTitleView1;
    UIView *subTitleView2;
    UILabel *placeholderLab;
    UILabel *textCountLab;
    UIView *textCountView;
}
@property(nonatomic, strong) UITextView *feedTv;
@property(nonatomic, strong) UITextField *phoneTf;
@property(nonatomic, strong) UIButton *submitBtn;
@end

@implementation FeedbackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubviews];
    [self addLayout];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"用户反馈"];
    MainViewController *mainVC = (MainViewController *)self.tabBarController;
    [mainVC hiddenTabBar];
}

-(void)addSubviews{
    subTitleView1 = [[UIView alloc] init];
    subTitleView1.backgroundColor = HTCFQuickRGBColor(240, 240, 240);
    [self.view addSubview:subTitleView1];
    
    subTitle1 = [[UILabel alloc] init];
    subTitle1.textColor = HTCFQuickRGBColor(102, 102, 102);
    subTitle1.text = @"问题和意见";
    [subTitleView1 addSubview:subTitle1];
    
    _feedTv = [[UITextView alloc] init];
    _feedTv.textContainerInset = UIEdgeInsetsMake(15, 16, 0, 20);
    _feedTv.font = [UIFont systemFontOfSize:16];
    _feedTv.delegate = self;
    _feedTv.returnKeyType = UIReturnKeyDone;
    [self.view addSubview:_feedTv];
    
    placeholderLab = [[UILabel alloc] init];
    placeholderLab.textColor = HTCFQuickRGBColor(142, 148, 154);
    placeholderLab.numberOfLines = 0;//表示label可以多行显示
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 8;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:16],
                                 NSParagraphStyleAttributeName:paragraphStyle
                             };
    placeholderLab.attributedText = [[NSAttributedString alloc] initWithString:@"请填写10个字以上的问题描述以便我们提供更好的帮助" attributes:attributes];
    [self.view addSubview:placeholderLab];
    
    
    textCountView = [[UIView alloc] init];
    textCountView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:textCountView];
    
    textCountLab = [[UILabel alloc] init];
    textCountLab.textColor = HTCFQuickRGBColor(142, 148, 154);
    textCountLab.text = @"0/200";
    [textCountView addSubview:textCountLab];
    
    subTitleView2 = [[UIView alloc] init];
    subTitleView2.backgroundColor = HTCFQuickRGBColor(240, 240, 240);
    [self.view addSubview:subTitleView2];
    
    subTitle2 = [[UILabel alloc] init];
    subTitle2.textColor = HTCFQuickRGBColor(102, 102, 102);
    subTitle2.text = @"联系方式";
    [subTitleView2 addSubview:subTitle2];
    
    _phoneTf = [[UITextField alloc] init];
    _phoneTf.placeholder = @"选填，便于我们与您联系";
    _phoneTf.backgroundColor = [UIColor whiteColor];
    //设置左边视图的宽度
    _phoneTf.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 0)];
    //设置显示模式为永远显示(默认不显示 必须设置 否则没有效果)
    _phoneTf.leftViewMode = UITextFieldViewModeAlways;
    _phoneTf.delegate = self;
    _phoneTf.returnKeyType = UIReturnKeyDone;
//    _phoneTf.keyboardType = UIKeyboardTypeNamePhonePad;
    [_phoneTf setValue:HTCFQuickRGBColor(160, 160, 160) forKeyPath:@"_placeholderLabel.textColor"];
    [self.view addSubview:_phoneTf];
    
    _submitBtn = [[UIButton alloc] init];
    _submitBtn.backgroundColor = HTCFQuickRGBColor(0, 203, 19);
    _submitBtn.titleLabel.textColor = [UIColor whiteColor];
    _submitBtn.layer.cornerRadius = 10;
    _submitBtn.layer.masksToBounds = YES;
    [_submitBtn addTarget:self action:@selector(submitData) forControlEvents:UIControlEventTouchUpInside];
    [_submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [self.view addSubview:_submitBtn];
}

-(void)addLayout{
    [subTitleView1 mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(self.view.mas_top);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 60));
    }];
    
    [subTitle1 mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(subTitleView1.mas_left).offset(20);
        make.centerY.equalTo(subTitleView1.mas_centerY);
    }];
    
    [_feedTv mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(subTitleView1.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 140));
    }];
    
    [placeholderLab mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(_feedTv.mas_top).offset(8);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-40, 60));
    }];
    
    [textCountView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(_feedTv.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 40));
        make.left.equalTo(self.view.mas_left);
    }];
    
    [textCountLab mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerY.equalTo(textCountView.mas_centerY);
        make.right.equalTo(textCountView.mas_right).offset(-20);
    }];
    
    [subTitleView2 mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(textCountView.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 60));
    }];
    
    [subTitle2 mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(subTitleView2.mas_left).offset(20);
        make.centerY.equalTo(subTitleView2.mas_centerY);
    }];
    
    [_phoneTf mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(subTitleView2.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 60));
    }];
    
    [_submitBtn mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(_phoneTf.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(60);
        make.right.equalTo(self.view.mas_right).offset(-60);
        make.height.equalTo(@50);
    }];

}


-(void)textViewDidChange:(UITextView *)textView

{
    // 判断是否有候选字符，如果不为nil，代表有候选字符
    if(textView.markedTextRange == nil){
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 8; // 字体的行间距
        paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
        
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],
                                     NSParagraphStyleAttributeName:paragraphStyle
                                   };
        textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
        textCountLab.text = [NSString stringWithFormat:@"%lu/200",(unsigned long)textView.text.length];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if (![text isEqualToString:@""]){
        placeholderLab.hidden = YES;
    }
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1){
        placeholderLab.hidden = NO;
    }
    if ([text isEqualToString:@"\n"]) {
        if (range.location == 0){
            placeholderLab.hidden = NO;
        }
        [textView resignFirstResponder];
        return NO;
    }
    if(range.location > 200){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"输入的字符数不能超过200"
                                                       delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField

{
    
    NSLog(@"textFieldDidBeginEditing");
    
    CGRect frame = textField.frame;
    
    CGFloat heights = self.view.frame.size.height;
    
    // 当前点击textfield的坐标的Y值 + 当前点击textFiled的高度 - （屏幕高度- 键盘高度 - 键盘上tabbar高度）
    
    // 在这一部 就是了一个 当前textfile的的最大Y值 和 键盘的最全高度的差值，用来计算整个view的偏移量
    
    int offset = frame.origin.y + 42- ( heights - 216.0-35.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    
    float width = self.view.frame.size.width;
    
    float height = self.view.frame.size.height;
    
    if(offset > 0){
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.frame = rect;
    }
    [UIView commitAnimations];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 64.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    return YES;
}

-(void)submitData{
    NSString *feedStr = _feedTv.text;
    NSString *phoneStr = _phoneTf.text;
    if([feedStr isEqualToString:@""]){
        [AppUtil showTipMessage:@"输入不能为空"];
        return;
    }
    if(feedStr.length<10){
        [AppUtil showTipMessage:@"反馈内容不能小于10"];
        return;

    }
    NSDictionary *feedbackParam = @{@"content":feedStr,@"phone":phoneStr};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:feedbackParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:feedbackParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    [HTTPPromise requestFeedbackParams:jsonData Success:^(id responseObj){
        NSLog(@"%@",responseObj);
        int code = [[responseObj objectForKey:@"ret"] intValue];
        if(code  == 0){
            [AppUtil showTipMessage:responseObj[@"desc"]];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error){
        NSLog(@"%@",error.userInfo);
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
